<template>
  <div class="chat-layout" :class="{ 'with-medical': store.showMedicalPanel, 'with-regulation': store.showRegulationPanel }">
    <!-- 左侧：模型选择（上半部分）和会话历史（下半部分） -->
    <div class="left-column">
      <!-- 上半部分：模型选择 -->
      <div class="left-section-1 model-selector">
        <ModelSelector />
      </div>
      
      <!-- 下半部分：会话历史 -->
      <div class="left-section-2 chat-history">
        <ChatHistory />
      </div>
    </div>

    <!-- 中间：聊天 -->
    <div class="middle-column" v-if="!store.showRegulationPanel">
      <!-- 普通聊天模式 -->
      <!-- 普通聊天模式 -->
      <div v-if="store.currentModule === 'blockchain'" class="normal-chat">
        <div class="chat" ref="chatRef">
          <div class="chat-content" ref="contentRef">
            <!-- 消息项 - 使用flex布局更便于控制顺序 -->
            <div
              v-for="(m, i) in store.messages"
              :key="i"
              :class="['msg', m.role === 'user' ? 'user' : 'assistant']"
            >
              <!-- AI消息：头像在左，气泡在右 -->
              <div v-if="m.role !== 'user'" class="avatar" aria-hidden="true">
                <span>AI</span>
              </div>
              
              <div class="bubble">
                <MarkdownRenderer :content="m.content" />
              </div>
              
              <!-- 用户消息：头像在右，气泡在左（放在气泡后面实现右对齐） -->
              <div v-if="m.role === 'user'" class="avatar" aria-hidden="true">
                <span>你</span>
              </div>
            </div>

            <div ref="endRef" class="scroll-anchor"></div>
          </div>
        </div>

        <div class="input-bar">
          <textarea
            v-model="input"
            :placeholder="placeholder"
            :disabled="store.streaming"
            @keydown.enter.exact.prevent="send"
          />
          <button class="btn primary" :disabled="!input.trim() || store.streaming" @click="send">发送</button>
          <button class="btn ghost" :disabled="!store.streaming" @click="abort">中断</button>
        </div>
      </div>

      <!-- 医疗对话模式（基于demo4.py） -->
      <div v-if="store.currentModule === 'medical'" class="medical-chat">
        <div class="medical-chat-header">
          <h3>🔍 Med-DistillFL影像分析工作台</h3>
        </div>
        
        <!-- 主内容区 -->
        <div class="medical-content">
          <!-- 输入侧边栏 -->
          <div class="input-sidebar">
            <div class="image-upload-section">
              <h4>📷 上传医学影像</h4>
              <div class="upload-area" :class="{ 'drag-over': dragOver }" 
                   @drop="handleDrop" 
                   @dragover.prevent="dragOver = true"
                   @dragleave="dragOver = false"
                   @click="triggerFileInput">
                <input ref="fileInput" type="file" accept="image/*" @change="handleFileSelect" style="display: none;">
                <div v-if="!selectedImage" class="upload-placeholder">
                  <div class="upload-icon">📁</div>
                  <p>点击或拖拽上传医学影像</p>
                  <p class="upload-hint">支持 JPG, PNG, DICOM 等格式</p>
                </div>
                <div v-else class="image-preview">
                  <img :src="imagePreviewUrl" alt="医学影像预览">
                  <button class="remove-image" @click.stop="removeImage">✕</button>
                </div>
              </div>
            </div>
            

            <!-- 分析指令输入 -->
            <div class="analysis-input">
              <label>分析指令</label>
              <textarea v-model="inputText" rows="2" 
                        placeholder="请输入您的问题..."></textarea>
            </div>

            <!-- RAG 模式开关 -->
            <div class="rag-control">
              <label class="rag-toggle">
                <input type="checkbox" v-model="ragEnabled">
                <span class="toggle-slider"></span>
                <span class="toggle-label">
                  🧠 知识图谱增强 (RAG)
                  <span class="rag-badge">实验性</span>
                </span>
              </label>
            </div>
            
            <!-- 操作按钮 -->
            <div class="action-buttons" v-show="true">
              <button class="btn primary analyze-btn" 
                      @click="startAnalysis" 
                      :disabled="!selectedImage || analyzing"  v-show="true">
                {{ analyzing ? '分析中...' : (hasInitialAnalysis ? '继续对话' : '开始分析') }}
              </button>
              <button class="btn secondary" @click="clearInput">清空输入</button>
            </div>
          </div>

          <!-- 聊天主界面 -->
          <div class="chat-main">
            <div class="chatbot-container" ref="medicalChatContainer">
              <!-- 💡 删除了欢迎占位符，直接显示消息列表 -->
              <div class="chat-messages">
                <div v-for="(message, index) in chatHistory" :key="index" 
                     class="message-item"
                     :class="{
                       'user-message': message.role === '用户',
                       'ai-message': message.role === 'AI'
                     }">
                  <!-- 💡 头像图标 -->
                  <div class="message-avatar">
                    <span v-if="message.role === '用户'">👤</span>
                    <span v-else>🤖</span>
                  </div>
                  
                  <!-- 💡 消息主体 -->
                  <div class="message-body">
                    <div class="message-header">
                      <span class="message-role-label">{{ message.role }}</span>
                      <span class="message-time">{{ formatTime(message.timestamp) }}</span>
                    </div>
                    <div class="message-content" v-html="renderMarkdown(message.content)"></div>                 
                  </div>
                </div>
              </div>
              <div v-if="analyzing" class="analyzing-indicator">
                <div class="spinner"></div>
                <span>AI正在分析医学影像，请稍候...</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 视频对话模式（使用 VideoPanel 组件） -->
      <div v-if="store.currentModule === 'video'" class="video-chat">
        <VideoPanel />
      </div>

      <!--MATH（使用 MathPanel 组件） -->
      <div v-if="store.currentModule === 'math'" class="math-chat">
        <MathPanel />
      </div>

      <!-- 计量检测模式：嵌入外部网页 (移动到这里) -->
<!--      <div v-if="store.currentModule === 'metrology'" class="metrology-chat">-->
<!--        <div style="display: flex; justify-content: center; align-items: center; height: 100%; font-size: 24px;">-->
<!--          Hello word!-->
<!--        </div>-->
<!--      </div>-->
      <div v-if="store.currentModule === 'metrology'" class="metrology-chat">
        <iframe
            v-show="!embedBlocked"
            :src="METROLOGY_EMBED_URL"
            title="计量检测"
            frameborder="0"
            referrerpolicy="no-referrer"
            allow="fullscreen; clipboard-read; clipboard-write"
            @load="onEmbedLoad"
          ></iframe>

        <div v-if="embedBlocked" class="embed-fallback">
          <p>目标站点拒绝被 iframe 嵌入（X\-Frame\-Options/CSP）。</p>
          <a class="btn primary" :href="METROLOGY_EMBED_URL" target="_blank" rel="noopener">在新标签页打开</a>
        </div>
      </div>
      <div v-if="store.currentModule === 'codeaudit'" class="codeaudit-chat">
        <CodeAuditPanel />
      </div>

      <div v-if="store.currentModule === 'supervision'" class="normal-chat">
        <div class="chat" ref="chatRef">
          <div class="chat-content" ref="contentRef">
            <!-- 消息项 - 使用flex布局更便于控制顺序 -->
            <div
              v-for="(m, i) in store.messages"
              :key="i"
              :class="['msg', m.role === 'user' ? 'user' : 'assistant']"
            >
              <!-- AI消息：头像在左，气泡在右 -->
              <div v-if="m.role !== 'user'" class="avatar" aria-hidden="true">
                <span>AI</span>
              </div>
              
              <div class="bubble">
                <MarkdownRenderer :content="m.content" />
              </div>
              
              <!-- 用户消息：头像在右，气泡在左（放在气泡后面实现右对齐） -->
              <div v-if="m.role === 'user'" class="avatar" aria-hidden="true">
                <span>你</span>
              </div>
            </div>

            <div ref="endRef" class="scroll-anchor"></div>
          </div>
        </div>

        <div class="input-bar">
          <textarea
            v-model="input"
            :placeholder="placeholder"
            :disabled="store.streaming"
            @keydown.enter.exact.prevent="send"
          />
          <button class="btn primary" :disabled="!input.trim() || store.streaming" @click="send">发送</button>
          <button class="btn ghost" :disabled="!store.streaming" @click="abort">中断</button>
        </div>
      </div>

    </div>

    <!-- 右侧：医疗影像分析面板 -->
    <div v-if="store.currentModule === 'medical'" class="right-column">
      <MedicalPanel />
    </div>
    <!-- 右侧：合约审计面板 -->
    <div v-if="store.showRegulationPanel" class="right-column regulation-column">
      <ContractAuditPanel />
    </div>
  </div>
</template>
<script setup lang="ts">
import { computed, ref, watch, nextTick, onMounted, onBeforeUnmount } from 'vue';
import {useChatStore} from '@/stores/chat';
import { API_BASE_URL, MODELS, METROLOGY_EMBED_URL } from '@/config/api'; // ← 新增 METROLOGY_EMBED_URL
import MarkdownRenderer from '@/components/MarkdownRenderer.vue';
import ModelSelector from '@/components/ModelSelector.vue';
import ChatHistory from '@/components/ChatHistory.vue';
import MedicalPanel from '@/components/MedicalPanel.vue';
import VideoPanel from '@/components/VideoPanel.vue';
import MathPanel from '@/components/MathPanel.vue';
import CodeAuditPanel from '@/components/CodeAuditPanel.vue';
import ContractAuditPanel from '@/components/ContractAuditPanel.vue';

const store = useChatStore();
const chatRef = ref<HTMLElement | null>(null);
const contentRef = ref<HTMLElement | null>(null); // ✅ 新增：内容容器
const endRef  = ref<HTMLElement | null>(null);   // ✅ 锚点

const input = ref('');
const placeholder = '请输入内容，Enter 发送。';

let controller: AbortController | null = null;

// 医疗对话模式的数据
const selectedImage = ref<File | null>(null);
const imagePreviewUrl = ref<string>('');
const inputText = ref('');
const dragOver = ref(false);
const fileInput = ref<HTMLInputElement | null>(null);

// 分析相关状态
const analyzing = ref(false);
const generatingReport = ref(false);

// 高级参数
const temperature = ref(0.8);
const topP = ref(0.4);

// 聊天历史和分析结果
const chatHistory = ref<Array<{role: string, content: string, timestamp: string}>>([]);
const medicalReport = ref<string>('');

// 医疗对话模式的滚动控制
const medicalChatContainer = ref<HTMLElement | null>(null);

// 用于存储已上传图像的服务器路径（供后续对话使用）
const uploadedImagePath = ref<string>('');
// 标识是否已完成首次全面分析
const hasInitialAnalysis = ref<boolean>(false);

// 计量检测 iframe 加载监控（若被拦截则显示提示）
const embedBlocked = ref(false);
let embedTimer: number | null = null;

function onEmbedLoad() {
  // 只要成功触发 load，认为未被拦截
  embedBlocked.value = false;
  if (embedTimer) {
    clearTimeout(embedTimer);
    embedTimer = null;
  }
}

// 进入计量检测时启动超时检测；若超时仍未 load，则判定被拦截
watch(() => store.currentModule, (m) => {
  if (m === 'metrology') {
    embedBlocked.value = false;
    if (embedTimer) clearTimeout(embedTimer);
    embedTimer = window.setTimeout(() => {
      if (!embedBlocked.value) embedBlocked.value = true;
    }, 2000);
  } else {
    if (embedTimer) {
      clearTimeout(embedTimer);
      embedTimer = null;
    }
  }
});

interface RagKnowledgeDetails {
  cases: Array<{
    case_id: string;
    original_report: string;
    images: string[];
    primary_findings: string[];
    detailed_descriptions: string[];
    negations: string[];
  }>;
  findings: string[];
  diseases: string[];
}

interface RagMetadataState {
  similarCasesCount: number;
  summaryFindings: string[];
  summaryDiseases: string[];
  details: RagKnowledgeDetails | null;
}

// ========== RAG 功能 ==========
const ragEnabled = ref<boolean>(false);  // RAG 模式开关
const ragAvailable = ref<boolean>(false);  // RAG 系统是否可用
const ragTopK = ref<number>(3);  // 检索相似病例数量
const ragMetadata = ref<RagMetadataState | null>(null);  // 最近一次检索的知识摘要（暂保留供后续扩展）

// 检查 RAG 系统状态
async function checkRagStatus() {
  try {
    const response = await fetch(`${API_BASE_URL}/api/rag/status`);
    if (response.ok) {
      const data = await response.json();
      ragAvailable.value = data.available;
      console.log('RAG 状态:', data);
    }
  } catch (error) {
    console.error('检查 RAG 状态失败:', error);
    ragAvailable.value = false;
  }
}

onBeforeUnmount(() => {
  if (embedTimer) {
    clearTimeout(embedTimer);
    embedTimer = null;
  }
});

onMounted(async () => {
  // 刷新后拉取会话列表（不自动选中）
  await store.fetchSessions();
  // 检查 RAG 系统状态
  await checkRagStatus();
});
async function ensureSessionIfNeeded(seedTitle?: string){
  if (store.currentSessionId) return;
  const id = await store.createSession();        // ✅ 不传参
  if (seedTitle) {
    await store.renameSession(id, seedTitle.slice(0, 40)); // ✅ 用首条消息做标题
  }
}

async function send(){
  const content = input.value.trim();
  if(!content || store.streaming) return;

  // 没有选中的会话则自动创建
  await ensureSessionIfNeeded(content);
  // 再次确认：如果仍没有会话，直接返回
  if(!store.currentSessionId) return;

  // 置顶当前会话（可选，但体验更好）
  store.touchSession(store.currentSessionId);

  store.appendMessage({ role:'user', content });
  store.appendMessage({ role:'assistant', content: '' });

  input.value = '';
  store.setStreaming(true);
  controller = new AbortController();

  const modelParam = MODELS[store.model].apiParam;

  try{
    const r = await fetch(`${API_BASE_URL}/api/chat/stream?session_id=${store.currentSessionId}&model=${modelParam}&module=supervision`, {
      method: 'POST',
      headers: { 'Content-Type':'application/json' },
      body: JSON.stringify({ messages: store.messages }),
      signal: controller.signal,
    });
    if(!r.ok || !r.body) throw new Error(`HTTP ${r.status}`);
    // 会话有新消息，更新“最近使用时间”并把它顶到列表前面
    store.touchSession(store.currentSessionId);
    const reader = r.body.getReader();
    const decoder = new TextDecoder('utf-8');
    let buffer = '';

    while(true){
      const { value, done } = await reader.read();
      if(done) break;
      buffer += decoder.decode(value, { stream: true });

      const parts = buffer.split('\n\n');
      for(let i=0; i<parts.length-1; i++){
        const chunk = parts[i];
        if(chunk.includes('data: ')){
          const payload = chunk.replace('data: ', '');
          if(payload !== '[DONE]') store.updateLastAssistantDelta(payload);
        }else{
          store.updateLastAssistantDelta(chunk);
        }
      }
      buffer = parts[parts.length-1];
    }

    // 流式响应完成后，检查是否需要翻译
    await translateIfEnglish();
  }catch(err){
    store.updateLastAssistantDelta(`\n\n> 请求中断或失败：${String(err)}`);
  }finally{
    store.setStreaming(false);
    controller = null;
  }

  // 直接翻译为中文
  async function translateIfEnglish() {
    if (!store.messages.length) return;
    
    const lastMessage = store.messages[store.messages.length - 1];
    if (lastMessage.role !== 'assistant') return;
    
    const content = lastMessage.content;
    console.log(content)
    
    try {
      console.log("调用百度翻译API进行实际翻译")
      // 这里使用简单的翻译方法，实际项目中可能需要调用专业的翻译API
      const translatedContent = await simpleTranslateToChinese(content);

      console.log("翻译后的结果:",translatedContent)
      
      // 更新最后一条消息为中文翻译
      if (translatedContent && translatedContent !== content) {
        // 先记录当前是否需要贴底
          const stickToBottom = shouldStick.value;
          // 更新内容
          // 更新内容
          
          // 解决方案：使用setTimeout添加微小延迟，确保Vue的响应式系统能够正确检测到变化
          // 先将内容设置为空字符串，再设置为翻译后的内容，强制触发重新渲染
          store.updateLastMessageContent('');
          await nextTick();


          store.updateLastMessageContent(translatedContent);
          // 强制触发重新渲染和滚动
          await nextTick();
          // 如果之前是贴底状态，则继续保持贴底
          if (stickToBottom) {
            scrollToEnd(true);
          }
          try {
            await fetch(`${API_BASE_URL}/api/sessions/${store.currentSessionId}/update-message`, {
              method: 'POST',
              headers: { 'Content-Type':'application/json' },
              body: JSON.stringify({ 
                message_index: store.messages.length - 1, 
                content: translatedContent,
                module: "supervision",
              }),
            });
          } catch (error) {
            console.error('同步翻译结果到后端失败:', error);
          }
        // store.updateLastMessageContent(translatedContent);
      }

     
    } catch (translationError) {
      console.error('翻译失败:', translationError);
      // 翻译失败不影响原有功能
    }
    // 新增：同步到后端
    
    
  }

    // 百度翻译API调用函数
    async function baiduTranslate(text: string): Promise<string> {
      try {
        // 发送POST请求到后端的翻译接口
        const response = await fetch(`${API_BASE_URL}/api/translate?module=supervision`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({ text: text })
        });

        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }

        const data = await response.json();
        
        // 解析翻译结果
        if (data.success && data.result) {
          // 根据后端修改后的返回格式，直接返回result字段的内容
          return data.result;
        }
        
        console.error('翻译结果解析失败:', data);
        return text; // 如果翻译失败，返回原文
      } catch (error) {
        console.error('翻译API调用失败:', error);
        return text; // 出错时返回原文
    }
  }

  // 简单的翻译实现，实际项目中应替换为专业的翻译API调用
  async function simpleTranslateToChinese(text: string): Promise<string> {
    // 这里使用真实的百度翻译API，能够识别代码块并保留不翻译
    
    
    // 翻译最后一个代码块后的文本（如果有
 
 
    return await baiduTranslate(text);
      
  }

}
function abort(){ if(controller) controller.abort(); }
onBeforeUnmount(() => { if(controller) controller.abort(); });


// 是否“贴底”状态（用户没主动往上滚）
const shouldStick = ref(true);
const SCROLL_TOL = 32; // 距离底部多少像素内视为“贴底”
function isAtBottom(el: HTMLElement){
  return el.scrollHeight - (el.scrollTop + el.clientHeight) <= SCROLL_TOL;
}
function onChatScroll(){
  if (!chatRef.value) return;
  shouldStick.value = isAtBottom(chatRef.value);
}
function autoScroll(force = false){
  const el = chatRef.value;
  if (!el) return;
  if (force || shouldStick.value) {
    // 想要动画可用 behavior: 'smooth'（流式时可能有轻微动画累积）
    el.scrollTo({ top: el.scrollHeight });
  }
}
// 用锚点滚到底；流式时用 behavior:'auto'，避免平滑动画落后
function scrollToEnd(force = false){
  const el = chatRef.value;
  const anchor = endRef.value;
  if (!el || !anchor) return;

  if (force || shouldStick.value) {
    // 双 rAF，等一轮/两轮布局（Markdown/公式/代码块）
    requestAnimationFrame(() => {
      requestAnimationFrame(() => {
        anchor.scrollIntoView({ block: 'end', behavior: 'auto' });
      });
    });
  }
}
// 移除重复的监听，避免滚动逻辑冲突
watch(() => store.messages.length, async () => {
  await nextTick();
  scrollToEnd(true);
});
// 仅保留一个流式增量的监听，使用 scrollToEnd 方法
watch(
  () => store.messages.length ? store.messages[store.messages.length - 1].content : '',
  async () => {
    await nextTick();
    scrollToEnd(false);
  }
);
onMounted(() => {
  chatRef.value?.addEventListener('scroll', onChatScroll, { passive: true });
});
onBeforeUnmount(() => {
  chatRef.value?.removeEventListener('scroll', onChatScroll);
});
// 观察“内容容器”尺寸变化（Markdown 渲染/代码高亮/数学公式/行号等都会触发）
let roContent: ResizeObserver | null = null;
onMounted(() => {
  if (contentRef.value) {
    roContent = new ResizeObserver(() => scrollToEnd(false));
    roContent.observe(contentRef.value);
  }
});
onBeforeUnmount(() => {
  roContent?.disconnect();
  roContent = null;
});
// 监听图片加载（子元素 load 冒泡不到父，但在捕获阶段能监听到）
function onImgLoad(){ scrollToEnd(false); }
onMounted(() => {
  chatRef.value?.addEventListener('load', onImgLoad, true); // useCapture = true
});
onBeforeUnmount(() => {
  chatRef.value?.removeEventListener('load', onImgLoad, true);
});

// 医疗对话模式的方法
const triggerFileInput = () => {
  fileInput.value?.click();
};

const handleFileSelect = (event: Event) => {
  const target = event.target as HTMLInputElement;
  const file = target.files?.[0];
  if (file) {
    setSelectedImage(file);
  }
};

const handleDrop = (event: DragEvent) => {
  event.preventDefault();
  dragOver.value = false;
  const file = event.dataTransfer?.files[0];
  if (file && file.type.startsWith('image/')) {
    setSelectedImage(file);
  }
};

const setSelectedImage = (file: File) => {
  // 如果更换了图像，重置分析状态
  if (selectedImage.value) {
    hasInitialAnalysis.value = false;
    uploadedImagePath.value = '';
    chatHistory.value = [];
    inputText.value = '';
  }
  
  selectedImage.value = file;
  const reader = new FileReader();
  reader.onload = (e) => {
    imagePreviewUrl.value = e.target?.result as string;
  };
  reader.readAsDataURL(file);
};

const removeImage = () => {
  selectedImage.value = null;
  imagePreviewUrl.value = '';
  if (fileInput.value) {
    fileInput.value.value = '';
  }
  // 重置分析状态
  hasInitialAnalysis.value = false;
  uploadedImagePath.value = '';
  chatHistory.value = [];
  inputText.value = '';
};

const startAnalysis = async () => {
  if (!selectedImage.value) return;
  
  // 如果没有输入文本，不允许提交
  if (!inputText.value.trim()) {
    alert('请输入您的问题');
    return;
  }
  
  analyzing.value = true;

  if (ragEnabled.value) {
    ragMetadata.value = null;
  }
  
  try {
    let response;
    let result;
    
    // 判断是首次分析还是后续对话
    if (!hasInitialAnalysis.value) {
      // 【首次分析】使用完整分析API
      console.log('执行首次全面分析...');
      
      const formData = new FormData();
      formData.append('image', selectedImage.value);
      formData.append('input_text', inputText.value);
      formData.append('temperature', temperature.value.toString());
      formData.append('top_p', topP.value.toString());
      
      // ⚡ 使用流式端点（根据 RAG 模式选择不同的 API）
      const endpoint = ragEnabled.value 
        ? `${API_BASE_URL}/api/medical/analyze-with-rag-stream`
        : `${API_BASE_URL}/api/medical/analyze-stream`;
      
      // 如果启用 RAG，添加 top_k 参数
      if (ragEnabled.value) {
        formData.append('top_k', ragTopK.value.toString());
      }
      
      console.log(`📡 使用端点: ${endpoint}`, ragEnabled.value ? '(RAG 增强模式)' : '(标准模式)');
      
      response = await fetch(endpoint, {
        method: 'POST',
        body: formData
      });
      
      if (response.ok) {
        
        
        
        // 添加用户输入到聊天历史
        chatHistory.value.push({
          role: '用户',
          content: inputText.value,
          timestamp: new Date().toISOString()
        });
        // 添加空的AI回复，用于实时更新
        const aiMessageIndex = chatHistory.value.length;
        chatHistory.value.push({
          role: 'AI',
          // content: result.analysis_result,
          content: '',
          timestamp: new Date().toISOString()
        });


         // ⚡ 读取SSE流式响应（新格式：JSON包装）
        const reader = response.body!.getReader();
        const decoder = new TextDecoder();
        let fullContent = '';
        
        while (true) {
          const { done, value } = await reader.read();
          if (done) break;
          
          const chunk = decoder.decode(value, { stream: true });
          const lines = chunk.split('\n');
          
          for (const line of lines) {
            if (line.startsWith('data: ')) {
              const data = line.substring(6).trim();
              
              if (data === '[DONE]') {
                console.log('✅ 流式分析完成');
                hasInitialAnalysis.value = true;
                break;
              }
              
              if (!data) continue;
              
              try {
                const parsedData = JSON.parse(data);
                
                // 💡 关键：处理不同类型的消息
                if (parsedData.type === 'metadata') {
                  // 💡 保存后端返回的图像路径
                  uploadedImagePath.value = parsedData.file_path;
                  console.log('📌 接收到元数据，图像路径:', parsedData.file_path);

                  if (parsedData.rag_enabled) {
                    ragMetadata.value = {
                      similarCasesCount: parsedData.similar_cases_count ?? 0,
                      summaryFindings: parsedData.knowledge_summary?.findings ?? [],
                      summaryDiseases: parsedData.knowledge_summary?.diseases ?? [],
                      details: parsedData.knowledge_details ?? null
                    };
                    console.log('📚 RAG 知识摘要:', ragMetadata.value);
                  } else {
                    ragMetadata.value = null;
                  }
                } else if (parsedData.type === 'content') {
                  // 💡 追加内容块
                  fullContent += parsedData.content;
                  chatHistory.value[aiMessageIndex].content = fullContent;
                } else if (parsedData.type === 'error') {
                  // 💡 显示错误
                  console.error('❌ 后端错误:', parsedData.error);
                  chatHistory.value[aiMessageIndex].content = `❌ 错误: ${parsedData.error}`;
                }
              } catch (e) {
                // 兼容旧格式（非JSON）
                console.warn('⚠️ 收到非JSON数据:', data);
                fullContent += data;
                chatHistory.value[aiMessageIndex].content = fullContent;
              }
            }
          }
        }
      }
    } else {
      // 【后续对话】使用流式对话API（本地模型或API）⚡
      console.log('执行后续对话（流式），使用图像路径:', uploadedImagePath.value);
      
      
      // 构建对话历史（只保留用户和AI的对话，排除系统消息）
      const history = chatHistory.value
        .filter(msg => msg.role === '用户' || msg.role === 'AI')
        .map(msg => ({
          role: msg.role === '用户' ? 'user' : 'assistant',
          content: msg.content
        }));
      
      response = await fetch(`${API_BASE_URL}/api/medical/continue-conversation-stream`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          image_path: uploadedImagePath.value,
          input_text: inputText.value,
          history: history,
          temperature: temperature.value,
          top_p: topP.value
        })
      });
      
      if (response.ok) {
        // 添加用户输入到聊天历史
        chatHistory.value.push({
          role: '用户',
          content: inputText.value,
          timestamp: new Date().toISOString()
        });
        
        // 添加空的AI回复，用于实时更新
        const aiMessageIndex = chatHistory.value.length;
        chatHistory.value.push({
          role: 'AI',
          content: '',
          timestamp: new Date().toISOString()
        });
        
        // ⚡ 读取SSE流式响应（新格式：JSON包装）
        const reader = response.body!.getReader();
        const decoder = new TextDecoder();
        let fullContent = '';
        
        while (true) {
          const { done, value } = await reader.read();
          if (done) break;
          
          const chunk = decoder.decode(value, { stream: true });
          const lines = chunk.split('\n');
          for (const line of lines) {
            if (line.startsWith('data: ')) {
              const data = line.substring(6).trim();
              
              if (data === '[DONE]') {
                console.log('✅ 后续对话流式完成');
                break;
              }
              
              if (!data) continue;
              
              try {
                const parsedData = JSON.parse(data);
                
                // 💡 关键：处理不同类型的消息（与首次分析相同）
                if (parsedData.type === 'content') {
                  // 💡 追加内容块
                  fullContent += parsedData.content;
                  chatHistory.value[aiMessageIndex].content = fullContent;
                } else if (parsedData.type === 'error') {
                  // 💡 显示错误
                  console.error('❌ 后端错误:', parsedData.error);
                  chatHistory.value[aiMessageIndex].content = `❌ 错误: ${parsedData.error}`;
                }
                // metadata 在后续对话中不会出现，所以不需要处理
              } catch (e) {
                // 兼容旧格式（非JSON）
                console.warn('⚠️ 收到非JSON数据:', data);
                fullContent += data;
                chatHistory.value[aiMessageIndex].content = fullContent;
              }
            }
          }
        }
      }
    }
    
    // 通用的错误处理
    if (!response.ok) {
      const errorMsg = '分析失败，请检查网络连接或稍后重试';
      chatHistory.value.push({
        role: '系统',
        content: errorMsg,
        timestamp: new Date().toISOString()
      });
    } else {
      // 清空输入框但保留图像
      inputText.value = '';
      // 滚动到底部显示新消息
      scrollToMedicalChatBottom();
    }
    
  } catch (error) {
    console.error('分析请求失败:', error);
    chatHistory.value.push({
      role: '系统',
      content: `分析请求失败：${error}`,
      timestamp: new Date().toISOString()
    });
  } finally {
    analyzing.value = false;
  }
};

const clearInput = () => {
  inputText.value = '';
  // 不清空聊天历史，只清空输入框
  // chatHistory.value = [];
  // medicalReport.value = '';
};

const generateReport = async () => {
  if (!chatHistory.value.length) return;
  
  generatingReport.value = true;
  
  try {
    const response = await fetch(`${API_BASE_URL}/api/medical/generate-report`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        chat_history: chatHistory.value,
        patient_info: {
          name: '患者',
          age: '未知',
          gender: '未知',
          history: '无'
        }
      })
    });
    
    if (response.ok) {
      const result = await response.json();
      medicalReport.value = result.report;
    } else {
      alert('报告生成失败');
    }
  } catch (error) {
    console.error('生成报告失败:', error);
    alert('报告生成失败');
  } finally {
    generatingReport.value = false;
  }
};

const downloadReport = () => {
  if (!medicalReport.value) return;
  
  const blob = new Blob([medicalReport.value], { type: 'text/plain;charset=utf-8' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = `患者_诊疗报告_${new Date().toISOString().split('T')[0]}.txt`;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  URL.revokeObjectURL(url);
};

const formatTime = (timestamp: string) => {
  return new Date(timestamp).toLocaleString('zh-CN');
};

const renderMarkdown = (content: string) => {
  // 简单的markdown渲染，处理基本格式
  return content
    .replace(/## (.*)/g, '<h2>$1</h2>')
    .replace(/### (.*)/g, '<h3>$1</h3>')
    .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
    .replace(/- (.*)/g, '<li>$1</li>')
    .replace(/\n/g, '<br>')
    .replace(/(<li>.*<\/li>)/g, '<ul>$1</ul>');
};

// 自动滚动到医疗对话底部
const scrollToMedicalChatBottom = () => {
  nextTick(() => {
    if (medicalChatContainer.value) {
      medicalChatContainer.value.scrollTop = medicalChatContainer.value.scrollHeight;
    }
  });
};

// 监听聊天历史变化，自动滚动到底部
watch(() => chatHistory.value.length, () => {
  scrollToMedicalChatBottom();
});

// 监听聊天内容变化，确保动态内容更新后也能滚动
watch(() => chatHistory.value, () => {
  scrollToMedicalChatBottom();
}, { deep: true });

// 监听分析状态变化，确保分析完成后滚动到底部
watch(() => analyzing.value, (newVal, oldVal) => {
  if (oldVal && !newVal) { // 从分析中变为分析完成
    scrollToMedicalChatBottom();
  }
});

// 添加ResizeObserver监听医疗聊天容器内容变化
let medicalResizeObserver: ResizeObserver | null = null;
onMounted(() => {
  if (medicalChatContainer.value) {
    medicalResizeObserver = new ResizeObserver(() => {
      scrollToMedicalChatBottom();
    });
    medicalResizeObserver.observe(medicalChatContainer.value);
  }
});
onBeforeUnmount(() => {
  medicalResizeObserver?.disconnect();
  medicalResizeObserver = null;
});
</script>

<style scoped>
.chat-layout{
  display: grid;  /* grid替换为flex */
  width: 100%;
  height: 100%;
  min-height: 0;
  grid-template-columns: 220px minmax(0, 1fr);  /* 添加 minmax 限制 */
  gap: 16px;
  overflow: hidden;  /* 防止溢出 */
}

/* 医疗模式下的三列布局 */
.chat-layout.with-medical {
  /* 左侧(历史) 200px；中间(工作区) 1fr；右侧(面板) 240px */
  grid-template-columns: 200px minmax(0, 1fr) 240px;
}

/* 两栏布局：当显示监管面板时（隐藏中间列） */
.chat-layout.with-regulation{
  grid-template-columns: 220px minmax(0, 1fr);  /* 左侧栏 + 右侧监管面板（占满剩余空间） */
}

/* 新增或修改：确保 metrology-chat 占满 middle-column 的空间 */
.metrology-chat {
  flex: 1;
  display: flex;
  width: 100%;
  height: 100%;
  overflow: hidden;
}

.placeholder-message {
  text-align: center;
  padding: 20px;
  color: #6b7280;
}

.placeholder-message h3 {
  font-size: 24px;
  color: #3b82f6;
  margin-bottom: 10px;
}

/* 确保 iframe 样式能够正确引用并覆盖 */
.metrology-chat iframe {
  flex: 1;
  width: 100%;
  height: 100%;
  border: none;
}

.video-chat {
  flex: 1 1 auto;
  min-height: 0;
  display: flex;
  overflow-y: auto;
  overflow-x: hidden;
}


.embed-fallback {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 12px;
  width: 100%;
  height: 100%;
  color: #6b7280;
  background: #fff;
}

/* 左侧栏整体样式 */
.left-column {
  display: flex;
  flex-direction: column;
  height: 100%;
  min-width: 0;
  min-height: 0;
}

/* 左侧上下两部分样式 */
.left-section-1 {
  width: 100%;
  overflow: auto;
  /* 上下各占50%高度 */
  flex: 4 1 70%;
  min-height: 0;
  box-sizing: border-box;
}

.left-section-2{
  width: 100%;
  overflow: auto;
  /* 上下各占50%高度 */
  flex: 1 1 30%;
  min-height: 0;
  box-sizing: border-box;
}

/* 模型选择部分 */
.model-selector {
  border-bottom: 1px solid var(--ui-border, #e5e7eb);
  padding-bottom: 8px;
}

/* 会话历史部分 */
.chat-history {
  padding-top: 8px;
}

/* 中间列（普通聊天和医疗聊天共用） */
.middle-column {
  display: flex;
  flex-direction: column;
  flex: 1;
  width: 100%;
  height: 100%; /* 或者 100%，确保占满可视区 */
  min-height: 0;
  overflow: hidden; /* 避免滚动冲突 */
}

.codeaudit-chat {
  flex: 1 1 auto;
  min-height: 0;
  display: flex;
  overflow-y: auto;  /* 添加垂直滚动 */
  overflow-x: hidden;
}

/* 右侧列（仅医疗模式显示） */
.right-column {
  min-width: 0;
  min-height: 0;
}

/* 让左右两列内部滚动而非整个页面滚动 */
.left .card,
.middle .history{
  flex: 1 1 auto;
  min-height: 0;
  overflow: auto;
}

/* 普通聊天模式 */
.normal-chat {
  display: grid;
  grid-template-rows: 1fr auto;
  gap: 10px;
  min-height: 0;
  height: 100%;
}

.normal-chat .chat {
  min-height: 0;
  width: 100%;          /* 防止出现"窄盒子" */
  overflow: auto;
}

/* 聊天内容区域样式 */
.chat-content {
  min-height: 0;
  overflow: auto;
}

/* 输入区 */
.input-bar{
  display: grid;
  grid-template-columns: 1fr auto auto;
  gap: 8px;
  align-items: end;
  padding: 8px 12px 12px;
  border-top: 1px solid var(--ui-border, #e5e7eb);
  background: var(--ui-surface, #fff);
}

.input-bar textarea{
  height: 92px;
  resize: none;
  padding: 10px 12px;
  border: 1px solid var(--ui-border, #e5e7eb);
  border-radius: 10px;
  outline: none;
  background: #fff;
  color: #000;
}

.btn{
  height: 40px;
  padding: 0 14px;
  border-radius: 10px;
  border: 1px solid transparent;
  cursor: pointer;
}

.btn.primary{
  background: #3b82f6;
  color: #fff;
}

.btn.ghost{
  background: #fff;
  border-color: #e5e7eb;
  color: #374151;
}

.btn.secondary {
  background: #6b7280;
  color: #fff;
}

/* 聊天气泡 */
.msg {
  display: flex;
  align-items: flex-start;
  gap: 8px;
  margin-bottom: 14px;
  max-width: 100%;
}

/* AI消息：左对齐 */
.msg.assistant {
  justify-content: flex-start;
}

/* 用户消息：右对齐 */
.msg.user {
  justify-content: flex-end;
}

/* 头像样式保持不变，但会根据消息类型自动调整位置 */
.avatar {
  width: 28px;
  height: 28px;
  border-radius: 50%;
  background: #e5e7eb;
  display: grid;
  place-items: center;
  font-size: 12px;
  color: #111827;
  flex-shrink: 0; /* 防止头像被压缩 */
}

/* 用户头像特殊样式 */
.msg.user .avatar {
  background: #dbeafe;
  color: #1e40af;
}

/* 气泡样式调整 */
.bubble {
  max-width: min(720px, 92%);
  padding: 10px 14px;
  border-radius: 14px;
  border: 1px solid var(--bubble-border, #e5e7eb);
  background: var(--bubble-bg, #fff);
  box-shadow: 0 1px 0 rgba(0,0,0,0.02);
}

/* AI气泡：左侧圆角小一点，区分视觉 */
.msg.assistant .bubble {
  --bubble-bg: #f7f9fd;
  --bubble-border: #e6ebf5;
  border-top-left-radius: 6px;
}

/* 用户气泡：右侧圆角小一点 */
.msg.user .bubble {
  --bubble-bg: #eef6ff;
  --bubble-border: #d7e7ff;
  border-top-right-radius: 6px;
}

.scroll-anchor { height: 1px; }

/* 医疗聊天模式样式 */
.medical-chat {
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden; /* 防止溢出 */
}

.medical-chat-header {
  padding: 16px;
  background: #f0fdfa;
  border-bottom: 1px solid #d1fae5;
}

.medical-chat-header h3 {
  margin: 0;
  color: #065f46;
}

.medical-content {
  display: flex !important;           /* 强制使用 Flex 布局 */
  flex-direction: row !important;     /* 强制水平排列 */
  width: 100%;
  gap: 24px;
  flex: 1;
  min-height: 0;
  padding: 24px;
  overflow: hidden;
  height: 100%; /* 确保占满可用空间 */
}

/* 医疗聊天容器样式 */
.chatbot-container {
  position: relative; /* 为绝对定位的子元素提供参照 */
  overflow-y: auto;
  overflow-x: hidden; /* 防止横向滚动 */
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  padding: 16px;
  height: 100%; /* 占满可用空间 */
  max-height: 100%; /* 限制最大高度 */
  width: 100%;
}

/* 确保滚动条可见 */
.chatbot-container::-webkit-scrollbar {
  width: 8px;
}

.chatbot-container::-webkit-scrollbar-track {
  background: #f1f5f9;
  border-radius: 4px;
}

.chatbot-container::-webkit-scrollbar-thumb {
  background: #cbd5e1;
  border-radius: 4px;
}

.chatbot-container::-webkit-scrollbar-thumb:hover {
  background: #94a3b8;
}

.input-sidebar {
  display: flex;
  flex-direction: column;
  /* 💡 关键修复：缩小左侧面板到 350px，为右侧留出更多空间 */
  flex-grow: 0 !important;            /* ❌ 禁止增长 (强制) */
  flex-shrink: 0 !important;          /* ❌ 禁止收缩 (强制) */
  flex-basis: 350px !important;       /* ⬅️ 修改为 350px */
  max-width: 350px !important; 
  height: 100%;
  overflow: auto; /* 允许内容溢出时滚动，避免按钮被裁切 */
  padding: 16px;
  background: linear-gradient(to bottom, #ffffff 0%, #fafbfc 100%);
  border-radius: 12px;
  box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.05);
}

.rag-control {
  flex: 0 0 auto;
  margin-bottom: 12px;
  padding: 14px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 10px;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.15);
}

.rag-toggle {
  display: flex;
  align-items: center;
  gap: 12px;
  cursor: pointer;
  user-select: none;
  position: relative;
}


.toggle-slider {
  position: relative;
  display: inline-block;
  width: 48px;
  height: 26px;
  background-color: rgba(255, 255, 255, 0.3);
  border-radius: 26px;
  transition: all 0.3s ease;
  flex-shrink: 0;
}

.toggle-slider::before {
  content: '';
  position: absolute;
  top: 3px;
  left: 3px;
  width: 20px;
  height: 20px;
  background-color: white;
  border-radius: 50%;
  transition: all 0.3s ease;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.toggle-label {
  color: white;
  font-weight: 600;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 8px;
}
.rag-toggle input[type="checkbox"]:checked + .toggle-slider {
  background-color: rgba(255, 255, 255, 0.9);
}

.rag-toggle input[type="checkbox"]:checked + .toggle-slider::before {
  transform: translateX(22px);
  background-color: #667eea;
}

.toggle-label {
  color: white;
  font-weight: 600;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.rag-badge {
  display: inline-block;
  padding: 2px 8px;
  background-color: rgba(255, 255, 255, 0.25);
  border-radius: 12px;
  font-size: 11px;
  font-weight: 500;
  letter-spacing: 0.5px;
}

.rag-options {
  margin-top: 12px;
  padding: 12px;
  background-color: rgba(255, 255, 255, 0.15);
  border-radius: 8px;
  backdrop-filter: blur(10px);
}

.rag-param {
  display: flex;
  align-items: center;
  gap: 8px;
  color: white;
  font-size: 13px;
  font-weight: 500;
}

.rag-input {
  width: 60px;
  padding: 6px 10px;
  border: 2px solid rgba(255, 255, 255, 0.3);
  border-radius: 6px;
  background-color: rgba(255, 255, 255, 0.9);
  color: #667eea;
  font-weight: 600;
  font-size: 14px;
  text-align: center;
  transition: all 0.2s ease;
}

.rag-input:focus {
  outline: none;
  border-color: white;
  box-shadow: 0 0 0 3px rgba(255, 255, 255, 0.2);
}

.rag-knowledge-card {
  margin-bottom: 14px;
  padding: 14px 16px;
  background: rgba(255, 255, 255, 0.12);
  border-radius: 10px;
  backdrop-filter: blur(8px);
  border: 1px solid rgba(255, 255, 255, 0.18);
  color: white;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.rag-knowledge-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-weight: 600;
}

.rag-knowledge-count {
  font-size: 12px;
  padding: 2px 8px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 999px;
}

.rag-knowledge-section {
  font-size: 13px;
}

.rag-knowledge-section ul {
  margin: 6px 0 0 16px;
  padding: 0;
  list-style: disc;
}

.rag-knowledge-case-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.rag-knowledge-case {
  padding: 10px;
  border-radius: 8px;
  background: rgba(14, 116, 144, 0.18);
  border: 1px solid rgba(255, 255, 255, 0.12);
}

.rag-knowledge-case .case-title {
  font-weight: 600;
  margin-bottom: 4px;
}

.rag-knowledge-case .case-report {
  font-size: 12px;
  line-height: 1.5;
  margin: 4px 0 8px;
  color: rgba(255, 255, 255, 0.85);
}

.rag-knowledge-case .case-findings {
  margin: 0;
  padding-left: 16px;
  font-size: 12px;
  list-style: square;
  color: rgba(255, 255, 255, 0.85);
}

.rag-knowledge-case .case-negations {
  margin-top: 6px;
  font-size: 12px;
  color: rgba(255, 255, 255, 0.75);
}

.image-upload-section {
  flex: 0 0 auto; /* 固定大小，不自动拉伸 */
  display: flex;
  flex-direction: column;
  max-height: 45%; /* 增加最大高度到45% */
}

.image-upload-section h4 {
  margin: 0 0 10px 0;
  color: #1f2937;
  font-size: 15px;
  font-weight: 600;
}

.upload-area {
  border: 2px dashed #3b82f6;
  border-radius: 12px;
  padding: 16px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  background: linear-gradient(135deg, #f9fafb 0%, #ffffff 100%);
  min-height: 180px;
  max-height: 220px;
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  overflow: hidden;
  position: relative;
}

.upload-area::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: radial-gradient(circle at center, rgba(59, 130, 246, 0.05) 0%, transparent 70%);
  opacity: 0;
  transition: opacity 0.3s ease;
  pointer-events: none;
}

.upload-area:hover::before,
.upload-area.drag-over::before {
  opacity: 1;
}

.upload-area:hover,
.upload-area.drag-over {
  border-color: #2563eb;
  background: linear-gradient(135deg, #eff6ff 0%, #f9fafb 100%);
  box-shadow: 0 4px 12px rgba(59, 130, 246, 0.15);
  transform: translateY(-2px);
}

.upload-placeholder .upload-icon {
  font-size: 40px;
  margin-bottom: 12px;
  filter: drop-shadow(0 2px 4px rgba(59, 130, 246, 0.2));
}

.upload-placeholder p {
  margin: 6px 0;
  color: #374151;
  font-size: 14px;
  font-weight: 500;
}

.upload-hint {
  font-size: 12px;
  color: #9ca3af;
  margin-top: 4px;
}

.image-preview {
  position: relative;
  border-radius: 12px;
  overflow: hidden;
  width: 100%;
  max-height: 190px;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #f9fafb;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.image-preview img {
  max-width: 100%;
  max-height: 180px;
  width: auto;
  height: auto;
  object-fit: contain;
  display: block;
}

.remove-image {
  position: absolute;
  top: 10px;
  right: 10px;
  background: rgba(239, 68, 68, 0.95);
  color: white;
  border: none;
  border-radius: 50%;
  width: 28px;
  height: 28px;
  cursor: pointer;
  font-size: 16px;
  font-weight: bold;
  display: grid;
  place-items: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  transition: all 0.2s ease;
  backdrop-filter: blur(4px);
}

.remove-image:hover {
  background: rgba(220, 38, 38, 1);
  box-shadow: 0 4px 12px rgba(220, 38, 38, 0.4);
  transform: scale(1.15);
}

.analysis-input {
  flex: 0 0 auto; /* 固定大小 */
  margin-bottom: 12px;
}

.analysis-input label {
  display: block;
  margin-bottom: 8px;
  font-size: 13px;
  color: #374151;
  font-weight: 600;
}

.analysis-input textarea {
  width: 100%;
  resize: none; /* 禁止手动调整大小 */
  padding: 12px 14px;
  border: 2px solid #e5e7eb;
  border-radius: 8px;
  min-height: 80px; /* 增加高度使输入更舒适 */
  max-height: 120px;
  font-size: 14px;
  line-height: 1.6;
  transition: all 0.2s ease;
  font-family: inherit;
  background: #ffffff; /* 统一为白色背景 */
  color: #0f172a;      /* 深色文字，提升可读性 */
}

.analysis-input textarea:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.analysis-input textarea::placeholder {
  color: #9ca3af;
}

.action-buttons {
  display: flex;
  gap: 10px;
  flex: 0 0 auto; /* 固定大小 */
  margin-bottom: 8px; /* 添加底部间距 */
}

.action-buttons .btn {
  flex: 1;
  padding: 14px 20px; /* 增大按钮内边距 */
  font-size: 15px;
  border-radius: 8px;
  font-weight: 600;
  min-height: 50px; /* 设置最小高度 */
  transition: all 0.2s ease;
  cursor: pointer;
}

.action-buttons .btn.primary {
  background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%);
  color: white;
  border: none;
  box-shadow: 0 2px 8px rgba(59, 130, 246, 0.3);
}

.action-buttons .btn.primary:hover:not(:disabled) {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(59, 130, 246, 0.4);
}

.action-buttons .btn.primary:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.action-buttons .btn.secondary {
  background: white;
  color: #6b7280;
  border: 2px solid #e5e7eb;
}

.action-buttons .btn.secondary:hover {
  background: #f9fafb;
  border-color: #d1d5db;
  transform: translateY(-1px);
}

.chat-main {
  min-width: 0;
  display: flex;
  flex-direction: column;
  height: 100%; /* 占满可用高度 */
  overflow: hidden; /* 防止溢出 */
}

.no-messages {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #d1d5db;
  position: relative;
}

.placeholder-content {
  position: absolute;
  top: 40%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
}

.placeholder-text {
  font-size: 16px;
  color: #d1d5db;
  margin: 0;
}

.chat-messages {
  padding-bottom: 80px; /* 为analyzing-indicator留出空间 */
}

/* ========================================
   💡 动画定义
   ======================================== */
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* ========================================
   💡 消息项布局 + 动画
   ======================================== */

.message-item {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  
  padding: 16px;
  border-radius: 12px;
  margin-bottom: 12px;
  max-width: 95%;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  line-height: 1.6;
  transition: all 0.2s ease;
  
  animation: fadeInUp 0.3s ease-out;
}

.message-item:last-child {
  margin-bottom: 0;
}

.message-avatar {
  font-size: 1.8rem;
  line-height: 1;
  margin-top: 2px;
  flex-shrink: 0;
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
}

.message-avatar span {
  filter: drop-shadow(0 1px 2px rgba(0, 0, 0, 0.1));
}

/* 用户头像背景 */
.user-message .message-avatar {
  background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%);
  box-shadow: 0 2px 8px rgba(99, 102, 241, 0.3);
}

/* AI 头像背景 */
.ai-message .message-avatar {
  background: linear-gradient(135deg, #10b981 0%, #059669 100%);
  box-shadow: 0 2px 8px rgba(16, 185, 129, 0.3);
}


.message-body {
  flex-grow: 1;
  display: flex;
  flex-direction: column;
  gap: 6px;
  min-width: 0;
}

.message-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.message-role {
  font-weight: 600;
  font-size: 0.9rem;
  color: #374151;
}

.message-role-label {
  font-weight: 600;
  font-size: 0.9rem;
  color: #374151;
}

/* 用户角色标签样式 */
.user-message .message-role-label {
  color: #6366f1;
}

/* AI 角色标签样式 */
.ai-message .message-role-label {
  color: #10b981;
}


.message-time {
  font-size: 12px;
  color: #9ca3af;
}

/* ========================================
   区分背景色
   ======================================== */

/* 用户的消息：浅灰色背景 */
.user-message {
  background-color: #f4f4f5;
  color: #333;
  border-left: 3px solid #6366f1;
}

/* AI 的消息：白色背景 */
.ai-message {
  background-color: #ffffff;
  color: #333;
  border-left: 3px solid #10b981;
}

/* Hover 效果 */
.message-item:hover {
  transform: translateX(4px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.message-item:hover .message-avatar {
  transform: scale(1.05);
  transition: transform 0.2s ease;
}


.message-content {
  line-height: 1.5;
  color: #374151;
}

/* AI 回答中的列表样式 */
.ai-message ul, 
.ai-message ol {
  padding-left: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
}

.ai-message li {
  margin-bottom: 6px;
}

/* 代码块样式优化 */
.message-content pre {
  background-color: #f8f9fa;
  padding: 12px;
  border-radius: 6px;
  overflow-x: auto;
  margin: 8px 0;
}

.message-content code {
  font-family: 'Courier New', Courier, monospace;
  font-size: 0.9em;
}

/* 链接样式 */
.message-content a {
  color: #6366f1;
  text-decoration: underline;
}

.analyzing-indicator {
  position: fixed;
  bottom: 24px;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 24px;
  background: rgba(239, 246, 255, 0.95);
  border-radius: 8px;
  color: #3b82f6;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  font-size: 14px;
  z-index: 100;
  backdrop-filter: blur(4px);
}

.spinner {
  width: 16px;
  height: 16px;
  border: 2px solid #93c5fd;
  border-top: 2px solid #3b82f6;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 适配 */
@media (max-width: 1200px){
  .chat-layout{
    grid-template-columns: minmax(180px, 220px) minmax(200px, 240px) minmax(0, 1fr);
  }

  .chat-layout.with-regulation{
    grid-template-columns: 180px minmax(0, 1fr);
  }
}

@media (max-width: 900px){
  .chat-layout{
    grid-template-columns: 1fr;
  }

  .chat-layout.with-regulation{
    grid-template-columns: 1fr;  /* 小屏幕时隐藏左侧栏，只显示监管面板 */
  }

  .chat-layout.with-medical {
    grid-template-columns: 1fr;
  }
  
  .right-column {
    display: none;
  }
  
  .medical-content {
    grid-template-columns: 1fr;
  }
}
/* 监管模式样式 */
.regulation-chat {
  height: 100%;
  background: var(--background);
}

.medical-chat-header {
  padding: 16px;
  background: var(--card);
  border-bottom: 1px solid var(--border);
}

.medical-chat-header h3 {
  margin: 0;
  font-size: 18px;
  color: var(--primary);
}

.medical-content {
  flex: 1;
  display: flex;
  min-height: 0;
  overflow: hidden;
  height: calc(100vh - 120px); /* 确保有固定高度 */
}

.input-sidebar {
  width: 300px;
  background: var(--card);
  border-right: 1px solid var(--border);
  padding: 16px;
  overflow-y: auto;
}

.image-upload-section {
  margin-bottom: 16px;
}

.image-upload-section h4 {
  margin: 0 0 8px 0;
  font-size: 14px;
  color: var(--foreground);
}

.upload-area {
  border: 2px dashed var(--border);
  border-radius: 8px;
  padding: 20px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  margin-bottom: 12px;
}

.upload-area:hover,
.upload-area.drag-over {
  border-color: var(--primary);
  background: var(--primary-foreground);
}

.upload-placeholder {
  color: var(--muted-foreground);
}

.upload-icon {
  font-size: 24px;
  margin-bottom: 8px;
}

.upload-hint {
  font-size: 11px;
  color: var(--muted-foreground);
  margin-top: 4px;
}

.image-preview {
  position: relative;
  display: inline-block;
}

.image-preview img {
  max-width: 100%;
  max-height: 200px;
  border-radius: 4px;
}

.remove-image {
  position: absolute;
  top: -8px;
  right: -8px;
  background: #ef4444;
  color: white;
  border: none;
  border-radius: 50%;
  width: 20px;
  height: 20px;
  cursor: pointer;
  font-size: 12px;
}

.advanced-params {
  margin-bottom: 16px;
  padding: 12px;
  background: var(--muted);
  border-radius: 4px;
}

.advanced-params h5 {
  margin: 0 0 8px 0;
  font-size: 12px;
  color: var(--foreground);
}

.param-row {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

.param-row label {
  font-size: 11px;
  color: var(--muted-foreground);
  min-width: 100px;
}

.slider {
  flex: 1;
  height: 4px;
  background: var(--border);
  border-radius: 2px;
  outline: none;
}

.analysis-input {
  margin-bottom: 16px;
}

.analysis-input label {
  display: block;
  margin-bottom: 4px;
  font-weight: 500;
  color: var(--foreground);
  font-size: 12px;
}

.analysis-input textarea {
  width: 100%;
  padding: 8px;
  border: 1px solid var(--border);
  border-radius: 4px;
  background: var(--background);
  color: var(--foreground);
  font-size: 12px;
  resize: vertical;
  min-height: 60px;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.analyze-btn {
  flex: 1;
}

.chat-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
  overflow: hidden;
}

.chatbot-container {
  flex: 1;
  overflow-y: auto;
  border: 1px solid var(--border);
  border-radius: 4px;
  padding: 12px;
  background: var(--background);
  margin: 16px;
  max-height: calc(100vh - 300px); /* 使用max-height而不是height */
  min-height: 300px; /* 设置最小高度 */
  height: auto; /* 让高度自适应内容 */
}

/* 确保滚动条可见 */
.chatbot-container::-webkit-scrollbar {
  width: 8px;
}

.chatbot-container::-webkit-scrollbar-track {
  background: var(--muted);
  border-radius: 4px;
}

.chatbot-container::-webkit-scrollbar-thumb {
  background: var(--border);
  border-radius: 4px;
}

.chatbot-container::-webkit-scrollbar-thumb:hover {
  background: var(--muted-foreground);
}

.no-messages {
  text-align: center;
  padding: 40px 20px;
  color: var(--muted-foreground);
  font-size: 14px;
}

.chat-messages {
  display: flex;
  flex-direction: column;
  gap: 16px;
  width: 100%;
  overflow-y: auto;
}

.message-item {
  border-bottom: 1px solid var(--border);
  padding-bottom: 12px;
}

.message-item:last-child {
  border-bottom: none;
}

.message-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.message-role {
  font-weight: 500;
  font-size: 12px;
  color: var(--primary);
}

.message-time {
  font-size: 10px;
  color: var(--muted-foreground);
}

.message-content {
  font-size: 14px;
  line-height: 1.5;
  color: var(--foreground);
  word-wrap: break-word;
  white-space: pre-wrap;
  overflow-wrap: break-word;
}

.analyzing-indicator {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 16px;
  color: var(--muted-foreground);
  font-size: 14px;
}

.spinner {
  width: 16px;
  height: 16px;
  border: 2px solid var(--border);
  border-top: 2px solid var(--primary);
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.report-section {
  background: var(--card);
  border-top: 1px solid var(--border);
  padding: 16px;
}

.report-actions {
  display: flex;
  gap: 8px;
  margin-bottom: 12px;
}

.report-content {
  max-height: 200px;
  overflow-y: auto;
  border: 1px solid var(--border);
  border-radius: 4px;
  padding: 12px;
  background: var(--background);
}

.markdown-content {
  line-height: 1.5;
  color: var(--foreground);
  font-size: 12px;
}

.markdown-content h2 {
  color: var(--primary);
  border-bottom: 1px solid var(--border);
  padding-bottom: 4px;
  margin: 16px 0 8px 0;
  font-size: 14px;
}

.markdown-content h3 {
  color: var(--foreground);
  margin: 12px 0 6px 0;
  font-size: 13px;
}

.markdown-content ul {
  margin: 8px 0;
  padding-left: 16px;
}

.markdown-content li {
  margin: 4px 0;
}

.markdown-content strong {
  color: var(--primary);
}
</style>